<?php 
class ProductModel extends Model{
	//商品表
	public $table='product';

	//获得商品属性
	public function getAttr($goods_gid=0){
		//商品ID
		$goods_gid=$goods_gid?$goods_gid:Q('goods_gid',0,'intval');
		//商品属性
		$sql="SELECT * FROM attribute  AS a JOIN goods_attr AS ga ON a.attr_id=ga.attr_id WHERE ga.goods_gid=$goods_gid AND attr_type=2 ORDER BY a.attr_id asc";
		$data=M()->query($sql);
		// p($data);
		//用来存放最终按不同属性分类的信息
		$attr=array();
		foreach ($data as $n => $d) {
			$attr[$d['attr_id']][]=$d;
		}
		return $attr;
	}

	//添加货品
	public function addProduct(){
		//商品属性
		$attrId=array();
		// p($_POST);exit;
		// p($_POST['attr']);
		foreach ($_POST['attr'] as $a) {
			foreach ($a as $n => $id) {
				$attrId[$n][]=$id;
			}			
		}
		// p($attrId);exit;
		foreach ($attrId as $n => $id) {
			//如果有属性为0的数据，即没有选择值，不插入货品表中(即没有办法确定的商品)
			if(array_search(0,$id)!==false){
				continue;
			}
			//货号与货品数量为空的数据也不插入到货品表中
			if(empty($_POST['product_sn'][$n]) || empty($_POST['product_number'][$n])){
				continue;
			}
			$data['goods_attr']=implode('-',$id);
			$data['product_sn']=$_POST['product_sn'][$n];
			$data['product_number']=$_POST['product_number'][$n];
			$data['goods_gid']=$_POST['goods_gid'];
			if(!$this->add($data)){
				$this->error='货品添加失败';
			}
		}
		return true;
	}

	public function getProduct($goods_gid=0){
		$goods_gid=$goods_gid?$goods_gid:Q('goods_gid',0,'intval');
		//获取某一个商品ID的货品信息
		$product=$this->where("goods_gid=$goods_gid")->all();
		foreach ($product as $id => $p) {
			$map['id']=array('IN',explode('-',$p['goods_attr']));
			$goods_attr_str=M('goods_attr')->where($map)->order('attr_id')->getField('attr_value',true);
			$product[$id]['goods_attr_str']=$goods_attr_str;
		}
		// p($product);exit;
		return $product;
	}

	public function delProduct(){
		$product_id=Q('product_id',0,'intval');
		// p($product_id);
		if(!$product_id){
			$this->error='货品不存在';
			return false;
		}else{
			return $this->del($product_id);
		}
	}

}

?>